<template>
    <!-- 供应商编辑页面 -->
    <div class="e-form">
        <div class="tabs warningTabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="资质信息"
                    name="aptitude"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="历史业绩"
                    name="firmPerformance"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="变更历史"
                    name="firmAdmin"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="评价历史"
                    name="evaluate"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="动态评价历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="解除处罚记录"
                    name="alteration"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        :rules="rules"
                                        label-width="150px"
                                        ref="formData"
                                    >
                                     <BillTop title="供应商库编辑" @cancel="handleClose"></BillTop>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="统一社会信用代码"
                                                    prop="creditCode"
                                                >
                                                    <el-input
                                                        v-model="
                                                            formData.creditCode
                                                        "
                                                        placeholder="请填写"
                                                        maxlength="18"
                                                        @change="
                                                            inputChange($event)
                                                        "
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="供应商名称"
                                                    prop="supplierName"
                                                >
                                                    <el-input
                                                        v-model="
                                                            formData.supplierName
                                                        "
                                                        placeholder="请填写"
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="24">
                                                <el-form-item
                                                    label="供应商类型"
                                                    prop="supplierTypeKey"
                                                >
                                                    <el-checkbox
                                                        style="
                                                            margin: 0px 30px 5px
                                                                0px;
                                                        "
                                                        :indeterminate="
                                                            isIndeterminate
                                                        "
                                                        v-model="checkAll"
                                                        @change="
                                                            handleCheckAllChange
                                                        "
                                                    >
                                                        全选
                                                    </el-checkbox>
                                                    <el-checkbox-group
                                                        v-model="
                                                            formData.supplierTypeKey
                                                        "
                                                        @change="
                                                            handleCheckedCitiesChange
                                                        "
                                                    >
                                                        <el-checkbox
                                                            v-for="item in typeList"
                                                            :key="item.kvId"
                                                            :label="item.kvKey"
                                                            :value="item.kvId"
                                                        ></el-checkbox>
                                                    </el-checkbox-group>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="注册地址"
                                                    prop="registerAddInfo"
                                                >
                                                    <SelectAddr
                                                        v-model="
                                                            formData.registerAddInfo
                                                        "
                                                        @getLabel="getAddrLabel"
                                                        lazy
                                                        showCountry
                                                        style="width: 100%"
                                                    ></SelectAddr>
                                                    <!-- 详细地址 -->
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12"></el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="联系电话"
                                                    prop="contactTel"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.contactTel
                                                        "
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="法人代表"
                                                    prop="deputy"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.deputy
                                                        "
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="传真" prop="fax">
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="formData.fax"
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="注册资本（万元）"
                                                    prop="registerCapital"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.registerCapital
                                                        "
                                                        v-enterFloat2
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="纳税类别："
                                                    prop="taxTypeName"
                                                >
                                                    <el-radio-group
                                                        @change="
                                                            radioChange($event)
                                                        "
                                                        v-model="
                                                            formData.taxTypeName
                                                        "
                                                    >
                                                        <el-radio
                                                            v-for="item in payTaxesTypeList"
                                                            :key="item.kvId"
                                                              :disabled="item.disabled"
                                                            :label="item.kvKey"
                                                            :value="
                                                                item.kvValue
                                                            "
                                                        ></el-radio>
                                                    </el-radio-group>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="邮箱"
                                                    prop="email"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="formData.email"
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="增值税一般纳税人资格查询"
                                                >
                                                    <a
                                                        href="https://etax.sichuan.chinatax.gov.cn/"
                                                        target="_blank"
                                                    >
                                                        查询
                                                    </a>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="邮编" prop="postCode">
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.postCode
                                                        "
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="信用信息查询"
                                                >
                                                    <a
                                                        href="http://www.gsxt.gov.cn/index.html"
                                                        target="_blank"
                                                    >
                                                        查询
                                                    </a>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="四川住房城乡建设厅信息查询"
                                                >
                                                    <a
                                                        href="http://202.61.88.188/xxgx/index.aspx"
                                                        target="_blank"
                                                    >
                                                        查询
                                                    </a>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="是否为境外单位"
                                                >
                                                    <el-switch
                                                        :width="60"
                                                        v-model="
                                                            formData.isAbroadUnit
                                                        "
                                                        class="main-el-switch"
                                                        active-color="#13ce66"
                                                        inactive-color="#D2D2D2"
                                                        active-value="1"
                                                        inactive-value="0"
                                                        active-text="是"
                                                        inactive-text="否"
                                                        @change="
                                                            isAbroadUnitChange
                                                        "
                                                    >
                                                    </el-switch>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="管理单位">
                                                    {{ formData.manageOrgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="信用等级">
                                                    <span>
                                                        {{
                                                            formData.creditLevel ==
                                                            '0'
                                                                ? '待定'
                                                                : formData.creditLevel ==
                                                                  '1'
                                                                ? 'A'
                                                                : formData.creditLevel ==
                                                                  '2'
                                                                ? 'B'
                                                                : formData.creditLevel ==
                                                                  '3'
                                                                ? 'C'
                                                                : formData.creditLevel ==
                                                                  '4'
                                                                ? 'D'
                                                                : formData.creditLevel ==
                                                                  '5'
                                                                ? 'S'
                                                                : ''
                                                        }}</span
                                                    >
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="状态：">
                                                    {{
                                                        statusLable(
                                                            formData.state
                                                        )
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-form-item label="录入人">{{
                                                formData.founderName
                                            }}</el-form-item>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>

                        <!-- ------------------------------------------------------------------------------------- -->
                    </div>

                    <!-- 资质信息 -->
                    <div id="aptitudeCon" class="con">
                        <div class="tabs-title" id="aptitude">资质信息</div>
                        <AptitudeIndex
                            :newQualifications="newQualifications"
                            @getAptitudeData="getAptitudeData"
                            :aptitudeSend.sync="aptitudeSend"
                            :aptitudeTables.sync="aptitudeTable"
                            bucketName="outer"
                             @setError="setError"
                            ref="aptitude"
                        />
                    </div>

                    <!-- 历史业绩 -->
                    <div id="firmPerformanceCon" class="con">
                        <div class="tabs-title" id="firmPerformance">
                            历史业绩
                        </div>
                        <KeyPerformance
                            :newFirmPerformance="newFirmPerformance"
                            :firmPerformanceTable.sync="firmPerformanceTable"
                            :firmPerformanceSend.sync="firmPerformanceSend"
                            @getFirmPerformanceData="getFirmPerformanceData"
                            bucketName="outer"
                             @setError="setError"
                            ref="firmPerformance"
                        />
                    </div>
                    <!-- 变更历史 -->
                    <div id="firmAdminCon" class="con">
                        <div class="tabs-title" id="firmAdmin">变更历史</div>
                        <ChangeHistory
                            :billId="billid"
                            :alterationTable="alterationTable"
                            ref="ChangeHistory"
                        />
                    </div>
                    <!-- 评价历史 -->
                    <div id="evaluateCon" class="con">
                        <div class="tabs-title" id="evaluate">评价历史</div>
                        <EvaluationHistory
                            :billId="billid"
                            ref="EvaluationHistory"
                        />
                    </div>
                    <!-- 动态评价历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">
                            动态评价历史
                        </div>
                        <DynamicEvaluationHistory
                            :billId="billid"
                            ref="DynamicEvaluationHistory"
                        />
                    </div>
                    <!-- 解除处罚记录 -->
                    <div id="alterationCon" class="con">
                        <div class="tabs-title" id="alteration">
                            解除处罚记录
                        </div>
                        <PunishmentReleaseRecord
                            :billType="parseInt(billid)"
                            ref="PunishmentReleaseRecord"
                        />
                    </div>
                    <!-- 审核历史 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">审核历史</div>
                        <ComExaHistory
                            :billType="parseInt(billid)"
                            @getAuditHistory="getAuditHistory"
                            :tableData="tableData"
                            ref="ComExaHistory"
                        />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <ComExaButtons
                :auditState="auditState"
                :state="parseInt(formData.state)"
                @exas="exas"
            />
            <el-button @click="cancel" size="small">取消</el-button>
        </div>
        <!-- <span style="display: none">{{ localPopConfirm }}</span> -->
    </div>
</template>

<script>
// 注册地址
import SelectAddr from '@/components/common/addrComp'
// 编辑接口
import Supplier from '@/api/OutsourcingartyAdmin/supplier/supplier'
// 变更接口
import supplierChange from '@/api/OutsourcingartyAdmin/supplier/supplierChange'
// 审核
import subcontractorChange from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorChange.js'
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import { getOrgById, getOrgByParentId } from '@/api/base/system'
// 资质信息
import AptitudeIndex from '@/pages/OutsourcingartyAdmin/supplierAdmin/supplier/qualifications'
// 历史业绩
import KeyPerformance from '@/pages/OutsourcingartyAdmin/supplierAdmin/supplier/keyPerformance'
// 变更历史
import ChangeHistory from '@/pages/OutsourcingartyAdmin/supplierAdmin/supplier/changeHistory'
// 评价历史
import EvaluationHistory from '@/pages/OutsourcingartyAdmin/supplierAdmin/supplier/evaluationHistory'
// 动态评价历史
import DynamicEvaluationHistory from '@/pages/OutsourcingartyAdmin/supplierAdmin/supplier/dynamicEvaluationHistory'
// 解除处罚记录
import PunishmentReleaseRecord from '@/pages/OutsourcingartyAdmin/supplierAdmin/supplier/punishmentReleaseRecord'
//审核历史
import ComExaHistory from '@/components/common/exaHistory.vue'
// 按钮
import ComExaButtons from '@/components/common/exaButtons'
//审核
import examine from '@/api/OutsourcingartyAdmin/subcontractorAdmin/examine.js'
import call from '@/api/OutsourcingartyAdmin/getAllType.js'
import { showSuccessPop, openAppClient, throttle, showLoading, hideLoading } from '@/utils/common'
// 作废
import { toVoid } from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractor.js'
import {
    creditCodeVerification,
    isPhone,
    isEmail,
    isName,
    isPostCode,
    isFax
} from '@/utils/rules'
export default {
    components: {
        SelectAddr,
        AptitudeIndex,
        KeyPerformance,
        ChangeHistory,
        DynamicEvaluationHistory,
        EvaluationHistory,
        PunishmentReleaseRecord,
        ComExaHistory,
        ComExaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            //表单数据
            formData: {
                creditCode: '', //统一社会信用代码
                supplierName: '', //供包商名称
                deputy: '', //法人代表
                registerAddInfo: '', //注册详细地址
                contactTel: '', //联系电话
                registerCapital: '', //注册资本
                fax: '', //传真
                email: '', //邮箱
                taxType: '', //纳税类别
                postCode: '', //邮编
                manageOrgName: '', //管理单位
                isAbroadUnit: '', //是否为境外单位
                enteringPerson: '', //录入人
                enteringDate: '', //录入时间
                creditLevel: '', //信用等级
                state: '', //状态
                supplierTypeValue: [], //供应商类型名称
                supplierTypeKey: [], //供应商类型id
                taxTypeName: '', //纳税类别名字
                taxTypeValue: '' //纳税类别id
            },
            //传给资质的值
            newQualifications: {
                billid: '', //单据id
                supplierTypeValue: [], //供应商名字id
                creditCode: this.creditCode, //信用代码
                isTableRowClass: true, //是否展示class
                isAbroadUnit: '' //是否是境外单位
            },
            //传给历史业绩的值
            newFirmPerformance: {
                billid: '', //单据id
                isTableRowClass: true, //是否展示class
                isAbroadUnit: '' //是否是境外单位
            },
            //类型列表
            typeList: [],
            payTaxesTypeList: [], //纳税类别列表
            aptitudeTable: [], //资质信息数据
            firmPerformanceTable: [], //历史业绩数据
            firmPerformanceSend: false, //历史业绩是否验证成功
            aptitudeSend: false, //资质信息是否验证成功
            isBaseSave: false, //基础是否保存
            alterationTable: [], //历史变更
            auditState: {}, //按钮状态
            newBaseData: {}, //处理过后的基础数据
            //是否为境外单位的单选
            radio: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            billid: '', //单据id
            winEvent: {}, //保存事件，跳转页面的时候，结束事件，优化性能
            lastConHeight: 0, //最后一个区域高度
            errorList: [], //错误标签
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            isIndeterminate: true,
            checkAll: false,
            tableData: [],
            // 审核对象
            commit: {
                billId: '', //	单据Id
                billType: 6041, //单据编码
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //	下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '' //审核意见
            },
            // 验证
            rules: {
                // 统一社会信用代码
                creditCode: [
                    {
                        required: true,
                        validator: creditCodeVerification,
                        trigger: 'blur'
                    }
                ],
                //供应商名称
                supplierName: [
                    {
                        required: true,
                        message: '请输入分包商名称',
                        trigger: 'blur'
                    }
                ],
                //类型
                supplierTypeKey: [
                    { required: true, message: '请选择类型', trigger: 'change' }
                ],
                //法人代表
                deputy: [
                    {
                        required: true,
                        validator: isName,
                        trigger: 'blur'
                    }
                ],
                //电话
                contactTel: [
                    {
                        required: true,
                        validator: isPhone,
                        trigger: 'blur'
                    }
                ],
                //邮箱
                email: [
                    {  validator: isEmail, trigger: 'blur' }
                ],
                //邮编
                postCode: [
                    {
                        validator: isPostCode,
                        trigger: 'blur'
                    }
                ],
                //传真
                fax: [
                    {
                        validator: isFax,
                        trigger: 'blur'
                    }
                ],
                //纳税类别
                taxTypeValue: [
                    {
                        required: true,
                        message: '请选择纳税类别',
                        trigger: 'change'
                    }
                ],
                //是否为境外单位
                isAbroadUnit: [
                    {
                        required: true,
                        message: '请选择是否为境外单位',
                        trigger: 'change'
                    }
                ],
                // 注册地址
                registerAddInfo: [
                    {
                        required: true,
                        message: '请选择注册地址',
                        trigger: 'change'
                    }
                ]
            }
        }
    },
    computed: {
        // 判断状态
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 102 - this.lastConHeight
        }
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.billid = this.$route.query.billid
        // 资质页面id
        this.newQualifications.billid = this.$route.query.billid
        // 历史业绩id
        this.newFirmPerformance.billid = this.$route.query.billid
        this.formData.orgId = data.userInfo.orgInfo.orgId
        this.formData.orgName = data.userInfo.orgInfo.orgName
        this.formData.orgId = data.userInfo.orgInfo.orgId //初始化机构id
        this.formData.orgName = data.userInfo.orgInfo.orgName //初始化机构名字
        this.formData.founderName = localStorage.getItem('userName')
        this.getTypeData() //进入页面获取类型选择框数据
        this.getTreeData(data.userInfo) //获取用户所在机构
        this.getBasicData() //获取基础数据
        this.getChangeList() //变更历史
        this.getCurrentUnitInfo() //获取流程按钮
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'aptitude',
            'firmPerformance',
            'firmAdmin',
            'evaluate',
            'auditHistory',
            'alteration',
            'accessory'
        ]
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    methods: {
        ...mapMutations(['setPopConfirm']),
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('accessoryCon')) {
                    const lastConHeight =
                        document.getElementById('accessoryCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        // 点击标签的方法
        onChangeTab (e) {
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
            this.queryData(e.name)
        },
        //根据点击不同的tab,调用不同的接口
        queryData (name) {
            switch (name) {
            // 基础信息
            case 'baseInfo':
                this.saveBase()
                this.saveBaseData()
                break
                // 资质信息
            case 'aptitude':
                this.getAptitudeData()
                break
                // 历史业绩
            case 'firmPerformance':
                this.getFirmPerformanceData()
                break
            }
        },
        // 变更历史列表查询
        async getChangeList () {
            let data = await supplierChange.supplierChangeList(this.billid)
            this.alterationTable = data
        },
        // 获取注册地址
        getAddrLabel (val) {
            this.formData.registerAdds = val
        },
        //获取基本信息数据
        async getBasicData () {
            let res = await Supplier.factualOutsourcerBase({ id: this.billid })
            // 判断供应商类型不为空，则转为数组
            if (res.supplierTypeKey) {
                res.supplierTypeKey = res.supplierTypeKey.split(',')
                // 调用选择方法，将数据选中
                this.handleCheckedCitiesChange(res.supplierTypeKey)
            }
            // 判断供应商类型不为空，则转为数组
            if (res.supplierTypeValue) {
                res.supplierTypeValue = res.supplierTypeValue.split(',')
            }
            //境外单位转为字符串
            res.isAbroadUnit = res.isAbroadUnit + ''
            // 调用判断境外单位的方法
            this.isAbroadUnitChange(res.isAbroadUnit)
            // 将请求回来的数据赋值
            this.formData = res
            // 初始化传给子组件的值
            this.newQualifications.creditCode = res.creditCode
            this.newQualifications.supplierTypeValue = res.supplierTypeValue //供应商类型
            this.newFirmPerformance.isAbroadUnit = res.isAbroadUnit
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 获取用户所在机构data
        async getTreeData (data) {
            const orgInfo = await getOrgById({
                orgId: data.orgInfo.orgId
            })
            // 如果类型是集团和分子公司，则管理机构为当前机构
            if (orgInfo.orgType == 1 || orgInfo.orgType == 2) {
                this.formData.manageOrgName = this.formData.orgName
                this.formData.manageOrgId = this.formData.orgId
            } else {
                // 否则通过机构id来查询父级机构，管理机构为父级机构
                const obj = await getOrgByParentId({
                    orgId: data.orgInfo.orgId
                })
                this.formData.manageOrgName = obj.parentId
                this.formData.manageOrgId = obj.parentName
            }
        },
        //获取供应商类型数据
        getTypeData () {
            call.getCredentialTree({ name: '外包方类型', id: '0' }).then(
                res => {
                    let id = ''
                    // 获取想要的类型id
                    res.map(item => {
                        if (item.kvKey == '供应商') {
                            id = item.kvId
                        }
                    })
                    call.getCredentialTree({
                        name: '外包方类型',
                        id: id
                    }).then(res => {
                        this.typeList = res
                    })
                }
            )
            call.getCredential('纳税类别').then(res => {
                this.payTaxesTypeList = res
            })
        },
        //保存按钮
        async save () {
            this.errorList = []
            // 调用资质信息验证方法并将值传到父组件
            this.$refs.aptitude.preserve()
            // 调用主营业绩验证方法并将值传到父组件
            this.$refs.firmPerformance.preserve()
            this.saveBase() //基础信息验证
            if (
                this.isBaseSave &&
                this.aptitudeSend &&
                this.firmPerformanceSend
            ) {
                Promise.all([
                    this.saveBaseData(), //基础信息
                    this.saveFirmPerformance(), //历史业绩
                    this.saveAptitude() //资质信息
                ])
                    .then(async () => {
                        this.clientPop('suc', '保存成功')
                    })
                    .catch(err => {
                        console.log('保存', err)
                        this.clientPop('err', '保存失败1')
                        this.scorllError()
                    })
            }
        },
        // 提交
        submit () {
            this.errorList = []
            // 调用资质信息验证方法并将值传到父组件
            this.$refs.aptitude.preserve()
            // // 调用主营业绩验证方法并将值传到父组件
            this.$refs.firmPerformance.preserve()
            //基础信息验证
            this.saveBase()
            if (
                this.isBaseSave &&
                this.aptitudeSend &&
                this.firmPerformanceSend
            ) {
                Promise.all([
                    this.saveBaseData(), //基础信息
                    this.saveFirmPerformance(), //历史业绩
                    this.saveAptitude() //资质信息
                ])
                    .then(async () => {
                        this.commit.billId = this.billid
                        subcontractorChange.findcommit(this.commit).then(() => {
                            this.clientPop('suc', '提交成功')
                            // 保存成功置空数据
                            this.firmPerformanceTable = []
                            this.aptitudeTable = []
                            this.$router.replace('/supplierbePutinstorage')
                        })
                    })
                    .catch(() => {
                        this.clientPop('err', '保存失败')
                        this.scorllError()
                    })
            }
        },
        //取消按钮
        cancel () {
            this.$router.replace('/supplierbePutinstorage')
        },
        // 全选
        handleCheckAllChange (val) {
            this.newQualifications.supplierTypeValue = []
            this.formData.supplierTypeKey = val
                ? this.typeList.map(item => {
                    return item.kvKey
                })
                : []
            this.isIndeterminate = false
            // 循环拿到id
            this.typeList.map(item => {
                this.formData.supplierTypeValue.push(item.kvValue)
                // 将全选的值赋给传给资质信息的对象
                this.newQualifications.supplierTypeValue.push(item.kvValue)
            })
            // 小规模纳税人禁用并自动切换成一般纳税人
            this.payTaxesTypeList.map(item => {
                if (item.kvValue == '1') {
                    this.$set(item, 'disabled', true)
                }
            })
            this.formData.taxTypeValue = '0'
            this.payTaxesTypeList.map(item => {
                if (this.formData.taxTypeValue == item.kvValue) {
                    this.formData.taxTypeName = item.kvKey
                }
            })
        },
        //外包方类型选择
        handleCheckedCitiesChange (value) {
            this.formData.supplierTypeValue = []
            this.newQualifications.supplierTypeValue = []
            let checkedCount = value.length
            this.checkAll = checkedCount === this.typeList.length
            this.isIndeterminate =
                checkedCount > 0 && checkedCount < this.typeList.length
            // 通过类型判断是否是小规模纳税人
            if (value.includes('其它') && checkedCount == 1) {
                this.payTaxesTypeList.map(item => {
                    if (item.kvValue == '1') {
                        this.$set(item, 'disabled', false)
                    }
                })
            } else {
                if (this.formData.taxTypeValue == '1') {
                    this.formData.taxTypeValue = '0'
                    this.payTaxesTypeList.map(item => {
                        if (this.formData.taxTypeValue == item.kvValue) {
                            this.formData.taxTypeName = item.kvKey
                        }
                    })
                }
                this.payTaxesTypeList.map(item => {
                    if (item.kvValue == '1') {
                        this.$set(item, 'disabled', true)
                    }
                })
            }
            // 循环拿到id
            this.typeList.map(item => {
                value.map(Valitem => {
                    if (item.kvKey == Valitem) {
                        this.formData.supplierTypeValue.push(item.kvValue)
                        // 将选中的值赋给传给资质信息的对象
                        this.newQualifications.supplierTypeValue.push(item.kvValue)
                    }
                })
            })
        },
        // 一般纳税人选择
        radioChange (row) {
            this.payTaxesTypeList.map(item => {
                if (row == item.kvKey) {
                    this.formData.taxTypeValue = item.kvValue
                }
            })
        },
        // 是否境外单位选择
        isAbroadUnitChange (val) {
            this.newQualifications.isAbroadUnit = val
            this.newFirmPerformance.isAbroadUnit = val
        },
        // 信用代码输入
        inputChange (val) {
            this.newQualifications.creditCode = val
        },
        // 基础信息
        saveBase () {
            // 调用资质信息验证方法并将值传到父组件
            this.$refs.formData.validate(async valid => {
                if (valid) {
                    // 如果外包商类型是数组则将数组转为字符串，否则不做处理
                    let datas = JSON.parse(JSON.stringify(this.formData))
                    if (datas.supplierTypeKey instanceof Array) {
                        datas.supplierTypeKey = datas.supplierTypeKey.join(',')
                    }
                    if (datas.supplierTypeValue instanceof Array) {
                        datas.supplierTypeValue =
                            datas.supplierTypeValue.join(',')
                    }
                    this.newBaseData = datas
                    this.isBaseSave = true
                } else {
                    this.isBaseSave = false
                    this.setError('baseInfo')
                }
            })
        },
        // 基础数据保存
        saveBaseData () {
            return new Promise((resolve, reject) => {
                if (this.isBaseSave) {
                    Supplier.factualBaseUpdate(this.newBaseData)
                        .then(() => {
                            resolve()
                            this.getBasicData()
                        })
                        .catch(err => {
                            reject(err)
                        })
                }
            })
        },
        // 资质信息删除
        async getAptitudeData (data) {
            // 如果有参数，则为删除时调用此方法，否则为保存
            if (data) {
                let data1 = []
                data1.push(data)
                await Supplier.supplierQualificationsAdd(data1)
            } else {
                this.$refs.aptitude.preserve()
                if (this.aptitudeTable.length > 0) {
                    await Supplier.supplierQualificationsAdd(
                        this.aptitudeTable
                    )
                }
            }
            this.$refs.aptitude.qualificationList(this.billid)
        },
        // 资质信息保存
        saveAptitude () {
            return new Promise((resolve, reject) => {
                if (!this.aptitudeSend) {
                    this.setError('aptitude')
                    reject('资质报错')
                    return
                }
                Supplier.supplierQualificationsAdd(this.aptitudeTable)
                    .then(() => {
                        resolve()
                        this.$refs.aptitude.qualificationList(this.billid)
                    })
                    .catch(err => {
                        this.setError('aptitude')
                        reject(err)
                    })
            })
        },
        // 历史业绩信息删除
        async getFirmPerformanceData (data) {
            // 如果有参数，则为删除时调用此方法，否则为保存
            if (data) {
                let data1 = []
                data1.push(data)
                await Supplier.supplierAchievementAdd(data1)
            } else {
                this.$refs.aptitude.preserve()
                if (this.firmPerformanceSend) {
                    await Supplier.supplierAchievementAdd(
                        this.firmPerformanceTable
                    )
                    this.$refs.aptitude.qualificationList(this.billid)
                }
            }
            this.$refs.firmPerformance.performanceList(this.billid)
        },
        // 历史业绩保存
        saveFirmPerformance () {
            return new Promise((resolve, reject) => {
                if (!this.firmPerformanceSend) {
                    reject('历史业绩报错')
                    return
                }
                console.log('lishi', this.firmPerformanceTable)
                Supplier.supplierAchievementAdd(this.firmPerformanceTable)
                    .then(() => {
                        resolve()
                        this.$refs.firmPerformance.performanceList(this.billid)
                    })
                    .catch(err => {
                        this.setError('firmPerformance')
                        reject(err)
                    })
            })
        },
        // 审核历史列表查询
        async getAuditHistory () {
            let data = await subcontractorChange.findByIdAuditHistory({
                billId: this.billid,
                billType: 6041,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            })
            this.tableData = data
        },
        // 去变更新增
        chengeNext () {
            let billid = this.billid
            this.$router.push({
                path: '/supplierbePutinstorageChangeAdd',
                query: { billid }
            })
        },
        // 审核
        audit () {
            // 审核之前调一次保存方法
            this.errorList = []
            // 调用资质信息验证方法并将值传到父组件
            this.$refs.aptitude.preserve()
            // // 调用主营业绩验证方法并将值传到父组件
            this.$refs.firmPerformance.preserve()
            //基础信息验证
            this.saveBase()
            if (
                this.isBaseSave &&
                this.firmPerformanceTable.length > 0 &&
                this.aptitudeTable.length > 0
            ) {
                Promise.all([
                    this.saveBaseData(), //基础信息
                    this.saveFirmPerformance(), //历史业绩
                    this.saveAptitude() //资质信息
                ])
                    .then(async () => {
                        // 客户端弹窗弹出本地页面
                        openAppClient('/exaDialog', '填写审核意见', () => {
                            // 审核拿到审核弹窗的意见
                            const auditParams = JSON.parse(
                                localStorage.vuex
                            ).auditParams
                            // 将审核意见赋值给参数传给后端
                            examine
                                .audit({
                                    billId: this.$route.query.billid,
                                    billType: 6041,
                                    freeNextUnitIndex: 0,
                                    freeNextUser: '',
                                    isPass: auditParams.isPass,
                                    isShareInAudit: true,
                                    opinion: auditParams.opinion
                                })
                                .then(() => {
                                    this.clientPop('suc', '审核成功')
                                    // 保存成功置空数据
                                    this.firmPerformanceTable = []
                                    this.aptitudeTable = []
                                    // 返回列表
                                    this.cancel()
                                })
                        }, null, null, null, 'small')
                    })
                    .catch(() => {
                        this.clientPop('err', '保存失败')
                        this.scorllError()
                    })
            }
        },
        // 删除方法
        ctDelete () {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                this.delent
            )
        },
        //删除回调
        delent () {
            this.$Ajax
                .httpGet({
                    url: '/outer/supplier/delete',
                    params: {
                        id: this.billid
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.replace('/supplierbePutinstorage')
                })
        },
        // 撤回
        withdrawChange () {
            this.clientPop('info', '是否确认撤回', this.callbackWithdraw)
        },
        // 撤回确认回调
        async callbackWithdraw () {
            let { code } = await examine.undoAudit({
                billId: this.billid, //单据id
                billType: '6041', //单据类型
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            })
            if (code == 200) {
                showSuccessPop('撤回成功')
                // 返回列表
                this.cancel()
            } else {
                showSuccessPop('撤回失败')
            }
        },
        // 作废
        toVoidChange () {
            this.clientPop('info', '是否确认作废', this.callback)
        },
        // 作废确认回调
        async callback () {
            // 客户端弹窗弹出本地页面
            const auditParams = JSON.parse(localStorage.vuex).auditParams
            openAppClient('/nullifyDialog', '单据作废原因', async () => {
                showLoading()
                await toVoid({
                    billId: this.billid, //单据id
                    billType: '6041', //单据类型
                    nullifyCreated: '',
                    nullifyCreator: '',
                    nullifyCreatorId: '',
                    nullifyDescription: auditParams.nullifyDescription,
                    nullifyReason: auditParams.nullifyReason
                })
                    .catch(() => {
                        this.clientPop('suc', '作废失败')
                    })
                hideLoading()
            })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.withdrawChange() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.toVoidChange() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        // 获取按钮状态
        getCurrentUnitInfo () {
            examine
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 6041,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
// 境外单位
::v-deep .clearPadding .vxe-cell {
    padding: 0;
}
::v-deep .clearPaddingLeft .vxe-cell {
    padding-left: 0px;
}
::v-deep {
    .main-el-switch {
        position: relative;
        .el-switch__core {
            height: 24px;
            border-radius: 12px;
            &:after {
                left: 4px;
                top: 3px;
            }
        }
        &.el-switch {
            &.is-checked {
                .el-switch__core {
                    &:after {
                        margin-left: -20px;
                        left: 100%;
                    }
                }
            }
        }
        &.is-checked {
            .el-switch__label--left {
                opacity: 0;
            }
            .el-switch__label--right {
                opacity: 1;
            }
        }
        .el-switch__label {
            position: absolute;
            top: 0;
        }
        .el-switch__label--left {
            right: 0;
            color: #999;
            z-index: 1;
            margin-right: 8px;
        }
        .el-switch__label--right {
            left: 0;
            color: #fff;
            opacity: 0;
            margin-left: 8px;
        }
    }
}
</style>
